// pages/cultivation/add/add.js
const http = require("../../../utils/request");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shake:true,
    change_data:{},
    imgs:[],
    company: [],
    vaule:"",
    dateTwoVisible: false,
    dateTwo: new Date().getTime(), // 支持时间戳传入
    // 指定选择区间起始值
    start: "2000-01-01",
    end: "2030-09-09",
    type:{
      manager: "主管",
      remark: "备注"
    },
    options: [],
    note1: '请选择公司',
    note2: '请选择农场',
    visible: false,
  },
  showCascader() {
    this.setData({ visible: true });
  },
  onChange(e) {
    const { selectedOptions } = e.detail;
    this.setData({
      note1: selectedOptions[0]?selectedOptions[0]['label']:'无',
      note2: selectedOptions[1]?selectedOptions[1]['label']:'无',
      [`change_data.companyId`]: selectedOptions[0]?selectedOptions[0]['value']:null,
      [`change_data.farmId`]: selectedOptions[1]?selectedOptions[1]['val']:null,
    });
  },
  change(v) {
    let index = v.currentTarget.dataset.data
    let value = v.detail.value
    let data = this.data.change_data
    data[index] = value
    this.setData({
      data,
    })
  },
  showPickerTwo(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`dateTwoVisible`]: true,
    });
  },
  hidePickerTwo() {
    const { mode } = this.data;
    this.setData({
      [`dateTwoVisible`]: false,
    });
  },
  onConfirmTwo(e) {
    const { value } = e.detail;
    const { mode } = this.data;
    console.log("confirm", value);
    let data = this.data.change_data
    data['time'] = value
    this.setData({
      [mode]: value,
      data,
      value:value
    });
    this.hidePickerTwo();
  },
  onColumnChangeTwo(e) {
    console.log("pick", e.detail.value);
  },
  input(e) {
    this.setData({
      value: e.detail.value
    })
  },
  onUpload(file) {
    const { imgs } = this.data;
    const { length } = imgs;
    this.setData({
      imgs: [...this.data.imgs,{...file,status:'loading'}],
      display: true
    });  
    const task = wx.uploadFile({
      url: 'https://37y5825u15.oicp.vip/admin/cos/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        this.setData({
          [`imgs[${length}].status`]: 'done',
          [`imgs[${length}].url`]: JSON.parse(res.data).data,
          [`change_data.picture[${length}]`]: JSON.parse(res.data).data,
          [`imgs[${length}].percent`]: res.progress,
          display: false,
        });
      },
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`imgs[${length}].percent`]: res.progress,
        [`imgs[${length}].status`]: 'loading',
      });
    });
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.onUpload(files[files.length-1]);
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { imgs } = this.data;
    imgs.splice(index, 1);
    let data = this.data.change_data
    data['picture'].splice(index,1)
    this.setData({
      imgs,
      data
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  cancel(){
    wx:wx.navigateBack({
      delta: 1,
      success: (res) => {
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  confirm(){
    if(!this.data.change_data['farmId']){
      wx:wx.showToast({
        title: '未设置农场！',
        icon: 'error'
      })
      return ;
    }
    if(this.data.shake){
      this.setData({
        shake: false,
      })
      http.postRequestBody('/admin/cultivation',JSON.stringify(this.data.change_data),res=>{
        wx:wx.showToast({
          title: '新增成功',
        })
        setTimeout(()=>{
          this.setData({
            shake: false,
          })
          this.onLoad();
          this.cancel();
        },900);
      },err=>{
        wx:wx.showToast({
          title: '失败！',
          icon: "error"
        })
        this.setData({
          shake: false,
        })
      })
    }else{
      wx:wx.showToast({
        title: '不要重复点击',
        icon: "error"
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    http.getRequest('/admin/company/all',{},res=>{
      this.setData({
        company: res.data.data
      })
      let data = res.data.data;
      let arr = [];
      for(let i = 0;i<data.length;i++){
        let chi = [];
        if(data[i]['farms']){
          for(let v of data[i]['farms']){
            chi.push({
              label: v['farmName'],
              value: data[i]['id']+''+v['id'],
              val: v['id']
            })
          }
        }
      arr.push({
        label: data[i]['companyName'],
        value: data[i]['id'],
        children: chi
      })
      this.setData({
        options: arr,
      })
    }
    },err=>{})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})